﻿using UnityEngine;
using System.Collections;

public class CollisionFloor
{
    public GameObject _gameObj;
    public Sphere[] _BottomSphere;
    public bool[] _bCollision;
    public float _radius;

    public bool bDown = false;
    public float collScale = 2.0f;
    public Vector3 _direction;
    public MoveDirection _modelDirection = MoveDirection.none;
    float _collGap = 2.0f;
    
    public void Reset()
    {
        bDown = false;
        _bCollision[0] = false;
        _bCollision[1] = false;
    }

    public float GetGapDistance()
    {
        return Vector2.Distance(_BottomSphere[0].center, _BottomSphere[1].center);
    }

    public double GetAngle()
    {
        return GameUtils.GetAngle(_BottomSphere[0].center, _BottomSphere[1].center);
    }

    public Vector3 GetPosition()
    {
        Vector3 totalPos;
        totalPos = (_BottomSphere[0].center + _BottomSphere[1].center) / 2;
        totalPos.y = totalPos.y;
        return totalPos;
    }

    public void UpdateDirection(MoveDirection dir)
    {
        double angle = GetAngle();

        Quaternion qt = new Quaternion();

        if (dir != MoveDirection.none)
            _modelDirection = dir;
        float objDirAngle = _modelDirection == MoveDirection.left ? 180.0f : 0.0f;

        qt = Quaternion.Euler(0, 0, (float)angle);
        // 모델때문에 추가적으로 90도 돌림.
        qt = qt * Quaternion.Euler(0, objDirAngle + 90, 0);
        _gameObj.transform.localRotation = qt;

        _direction = Quaternion.Euler(0, 0, (float)angle) * Vector3.right;
        
    }

    public void DownBottomCollision(int idx, Vector3 srcForce)
    {
        Vector3 downForce = srcForce;
        float noCollDownForce = _BottomSphere[idx].radius / 2;
        _bCollision[idx] = false;
        downForce.y -= noCollDownForce;

        // 이부분을 추가적으로 수정해야함.
        if (Vector3.Distance(_BottomSphere[0].center + downForce, _BottomSphere[1].center) < 30)
            _BottomSphere[idx].center += downForce;

    }

    public CollisionFloor( GameObject obj, GameObject[] testSphere )
    {
        _gameObj = obj;
        _direction = Vector3.right;

        _BottomSphere = new Sphere[2];
        _bCollision = new bool[2];

        _collGap = 2.0f;
        float radius = obj.transform.localScale.x / 4;
        _radius = radius;

        _BottomSphere[0] = new Sphere();
        _BottomSphere[0].center = new Vector3(obj.transform.localPosition.x - (radius / _collGap), obj.transform.localPosition.y, obj.transform.localPosition.z);
        _BottomSphere[0].radius = radius * collScale;

        _BottomSphere[1] = new Sphere();
        _BottomSphere[1].center = new Vector3(obj.transform.localPosition.x + (radius / _collGap), obj.transform.localPosition.y, obj.transform.localPosition.z);
        _BottomSphere[1].radius = radius * collScale;
    }
   
}
